#include <No7/Core/Scene/SceneManager.h>
#include <No7/MathTool/Matrixes.h>

#include "MainScene.h"
#include "GameScene.h"
#include "GlobalVariables.h"
#include "GlobalMacros.h"

#pragma comment(lib, "Winmm.lib")

void loadResources()
{
	AddFontResourceEx(_T("Resources/IPix.ttf"), FR_PRIVATE, NULL);
}

void createScenes()
{
	Core::Scene* main_scene = new MainScene();
	Core::Scene* game_scene = new GameScene();
	scene_manager->addScene(1, main_scene);
	scene_manager->addScene(2, game_scene);
}

void initMatrixes()
{
	MathTool::MatrixFactoryIn2D::generateScaleMatrix(1.0l, 1.0l);
	MathTool::MatrixFactoryIn2D::generateRotateMatrix(0.0l);
	MathTool::MatrixFactoryIn2D::generateTranslateMatrix(0.0l, 0.0l);
	MathTool::MatrixFactoryIn2D::generateModelTransformationMatrix();
	MathTool::MatrixFactoryIn2D::generateViewTransformationMatrix(0.0l, 0.0l);
	MathTool::MatrixFactoryIn2D::generateProjectionTransformationMatrix(-WINDOW_WIDTH / 2, WINDOW_WIDTH / 2, -WINDOW_HEIGHT / 2, WINDOW_HEIGHT / 2);
	MathTool::MatrixFactoryIn2D::generateViewportTransformationMatrix(WINDOW_WIDTH, WINDOW_HEIGHT);
	MathTool::MatrixFactoryIn2D::generateFinalMatrix();
}

void init()
{
	loadResources();
	createScenes();
	initMatrixes();
}

void mainLoop()
{
	scene_manager->switchToSceneByID(1);
	ExMessage msg;
	int FPS = 60;
	while (!if_break)
	{
		DWORD frame_start_time = GetTickCount();
		while (peekmessage(&msg))
		{
			scene_manager->onInput(msg);
		}
		static DWORD last_tick_time = GetTickCount();
		DWORD current_tick_time = GetTickCount();
		DWORD delta_tick = current_tick_time - last_tick_time;
		scene_manager->onUpdate(delta_tick);
		last_tick_time = current_tick_time;
		BeginBatchDraw();
		cleardevice();
		scene_manager->onDraw();
		EndBatchDraw();
		DWORD frame_end_time = GetTickCount();
		DWORD frame_delta_time = frame_end_time - frame_start_time;
		if (frame_delta_time < 1000 / FPS)
		{
			Sleep(1000 / FPS - frame_delta_time);
		}
	}
	Core::SceneManager::destroyInstance();
}

int main()
{
	init();
	mainLoop();
	return 0;
}